// pages/createRoom/createRoom.js
Page({
  data: {
    RoomName:'',
    RoomDiscription:'',
    RoomPassword:''
  },

  onLoad(options) {},

  onShow() {},

  InputChange: function (e) {
    let field = e.currentTarget.dataset.field; 
    let value = e.detail.value; 

    // 更新页面数据
    this.setData({
      [field]: value
    });
  },

  InputName: function (e) {
    this.setData({
      RoomName: e.detail.value
    });
  },
  InputDiscription: function (e) {
    this.setData({
      RoomDiscription:e.detail.value
    });
    console.log(this.data.RoomDiscription);
  },
  InputPassword: function (e) {
    this.setData({
      RoomPassword: e.detail.value
    });
  },

  // 将输入内容整合成一项，填入缓存中的房间数组并发送到后端
  Create_Room: function () {
    let roomList = wx.getStorageSync('RoomList') || [];

    let newRoom = {
      roomId:roomList.length + 1,
      roomName:this.data.RoomName,
      roomDiscription:this.data.RoomDiscription,
      roomPassword:this.data.RoomPassword
    };

    if (!newRoom.roomName) {
      wx.showToast({
        title: '请填写完整信息',
        icon: 'none'
      });
      return;
    }

    wx.request({
      url: 'http://localhost:3000/AddRoom', // 替换为你的后端地址
      method: 'POST',
      header: {  
        'content-type': 'application/json', // 根据需要设置  
        'Authorization': wx.getStorageSync('usertoken')
      },  
      data: {
        rname: newRoom.roomName,
        rdis: newRoom.roomDiscription,
        rpass: newRoom.roomPassword
      },
      success: (res) => {
        if (res.data.code === 208) {
          roomList.push(newRoom);
          wx.setStorageSync('RoomList', roomList);
          let roomId = res.data.response.roomid;
          console.log(roomId);
          wx.setStorageSync('RoomId', roomId);
          wx.showToast({
            title: '房间创建成功',
            icon: 'success'
          });
          wx.navigateTo({
            url: '/pages/room/room?roomId=' + newRoom.roomId,
          });
        }  if(res.data.code === 401){
          utils.userlogin();
        }
      },
      fail: () => {
        wx.showToast({
          title: '请求失败',
          icon: 'none'
        });
      }
    });
    
  },

})
